/**
 * 
 */
package cn.edu.nju.ws.sview.wyge.relations.adataset.entities;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import cn.edu.nju.ws.sview.database.DBConnectionFactory;
import cn.edu.nju.ws.sview.wyge.relations.adataset.CustomDataset;

/**
 * @author Weiyi Ge (geweiyi@gmail.com) 2012-7-28
 * 
 */
public class BNodeFinder {
	/**
	 * 如果是-1没有作为主语，0没有type，其他有type
	 * 
	 * @param ds_type
	 * @param ds_id
	 * @param subject
	 * @return
	 */
	public static boolean find(String ds_type, int ds_id, String subject) {
		ArrayList<Integer> docs = null;
		if (ds_type.equals("custom")) {
			docs = CustomDataset.getURLIDsByCustomDatasetId(ds_id);
		} else if (ds_type.equals("uri")) {
			docs = new ArrayList<Integer>();
			docs.add(ds_id);
		}
		return find(docs, subject);
	}

	public static boolean find(ArrayList<Integer> docs, String subject) {
		boolean hasNode = false;
		String docstring = "";
		for (int doc : docs) {
			docstring += doc + ",";
		}
		docstring = docstring.substring(0, docstring.length() - 1);
		try {
			Connection con = DBConnectionFactory.getConnection();//.getFalconConnection();
			ArrayList<String> objs = new ArrayList<String>();
			Statement stmt = con.createStatement();
			ResultSet rs = stmt
					.executeQuery("SELECT distinct o FROM quadruple where doc_id in ("
							+ String.format("%s", docstring)
							+ ") and o like 'b%'");
			while (rs.next()) {
				objs.add(rs.getString(1));
			}
			rs.close();

			if (objs.size() > 0) {
				String ostring = "";
				for (String obj : objs) {
					ostring += "\"" + obj + "\",";
				}
				ostring = ostring.substring(0, ostring.length() - 1);

				ResultSet rs2 = stmt.executeQuery("SELECT * from quadruple "
						+ "where s not in (" + ostring + ") " + "and s = \""
						+ subject + "\" and doc_id in ("
						+ String.format("%s", docstring) + ") limit 1");// 只在主语部分出现的blank
				// node
				if (rs2.next()) {
					hasNode = true;
				}
				rs2.close();
			} else {
				ResultSet rs2 = stmt
						.executeQuery("SELECT distinct s from quadruple "
								+ "where s = \"" + subject + "\" and doc_id in ("
								+ String.format("%s", docstring) + ") limit 1");// 只在主语部分出现的blank
				// node
				if (rs2.next()) {
					hasNode = true;
				}
				rs2.close();
			}
			stmt.close();
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return hasNode;
	}
}
